package org.healthy.base;

import org.healthy.base.constant.RedisKeyConst;
import org.healthy.util.JedisOper;
import org.healthy.utils.pub.exception.ExceptionEnums;
import org.healthy.utils.pub.exception.ServiceException;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import javax.annotation.Resource;

/**
 * Created by qingshengzheng on 15/11/18.
 */
public abstract class BaseService {
    public static String UTF_8 = "UTF-8";
    @Resource(name = "shardedJedisPool")
    private ShardedJedisPool shardedJedisPool;

    public ShardedJedis getShardedJedis() {
        return shardedJedisPool.getResource();
    }

    public JedisOper getJedisOper() {
        return new JedisOper(getShardedJedis(), shardedJedisPool, true);
    }

    public JedisOper getJedisOper(Boolean autoReturn) {
        return new JedisOper(getShardedJedis(), shardedJedisPool, autoReturn);
    }



    /**
     * 抛出异常
     *
     * @param exceptionEnums
     */
    protected void throwException(ExceptionEnums exceptionEnums) {
        throw new ServiceException(exceptionEnums);
    }


    public String getKey(String keyPrefix, Object... params) {
        StringBuffer temp = new StringBuffer(keyPrefix);
        for (Object param : params) {
            if (param == null) continue;
            ;
            temp.append(":").append(param.toString());
        }
        return temp.toString();
    }


    public Long getDelStopPosition(String key) {
        Long count = getJedisOper().zcount(key, 0L, Long.MAX_VALUE);
        if (count <= 1000) return null;
        else return count - 1000;
    }

    public void delRevSortCache(String key) {
        Long stop = getDelStopPosition(key);
        if (stop != null)
            getJedisOper().zremrangeByRank(key, 0L, stop);
    }

}
